//
//  RGPhoneViewController.m
//  Gunz
//
//  Created by Joggy on 16/1/20.
//  Copyright © 2016年 NUPT. All rights reserved.
//

#import "RGPhoneViewController.h"
#import "GZNetRequest.h"
#import <SMS_SDK/SMSSDK.h>
#import "CoreStatus.h"
#import "QYNotice.h"
#import "GZConst.h"

@interface RGPhoneViewController ()

@end

static CGFloat textBottom = 0;
static CGRect viewOrigin;

@implementation RGPhoneViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    [self prepareForNav];
    [self prepareForLayout];
    UITapGestureRecognizer *endEditTap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(endEditTap)];
    [self.view addGestureRecognizer:endEditTap];
}

-(void)viewDidAppear:(BOOL)animated {
    [super viewDidAppear:animated];
    viewOrigin = self.view.frame;
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillShow:) name:UIKeyboardWillShowNotification object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillHide:) name:UIKeyboardWillHideNotification object:nil];
}

-(void)viewDidDisappear:(BOOL)animated {
    [super viewDidDisappear:animated];
    [[NSNotificationCenter defaultCenter] removeObserver:self name:UIKeyboardWillShowNotification object:nil];
    [[NSNotificationCenter defaultCenter] removeObserver:self name:UIKeyboardWillHideNotification object:nil];
}

- (void)prepareForNav {
    [super prepareForNav];
    self.title = @"账号注册";
    //返回按键
    UIImage *leftImage = [UIImage imageNamed:@"all_back"];
    UIButton *leftButton = [[UIButton alloc] initWithFrame:CGRectMake(0, 0, (leftImage.size.width/leftImage.size.height)*22, 22)];
    [leftButton setImage:leftImage forState:UIControlStateNormal];
    [leftButton addTarget:self action:@selector(back) forControlEvents:UIControlEventTouchUpInside];
    UIBarButtonItem *leftBarItem = [[UIBarButtonItem alloc] initWithCustomView:leftButton];
    [self navigationItem].leftBarButtonItem = leftBarItem;
}

- (void) prepareForLayout {
    [super prepareForLayout];
    //滚动视图
    scroll = [[UIScrollView alloc] initWithFrame:CGRectMake(0, 0, screenWidth, screenHeight - 64)];
    scroll.contentSize = CGSizeMake(screenWidth, screenHeight + 1 - 64);
    scroll.showsHorizontalScrollIndicator = false;
    scroll.showsVerticalScrollIndicator = false;
    scroll.delegate = self;
    //号码框
    UIView *phoneView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 66, RGTextHeihgt)];
    _phoneNumLabel = [[UILabel alloc] init];
    _phoneNumLabel.text = @"手机号码 : ";
    _phoneNumLabel.font = [UIFont systemFontOfSize:font15];
    _phoneNumLabel.alpha = 0.7;
    [_phoneNumLabel sizeToFit];
    _phoneNumLabel.layer.position = CGPointMake(_phoneNumLabel.frame.size.width/2, phoneView.frame.size.height/2);
    [phoneView addSubview:_phoneNumLabel];
    _phoneNumText = [[UITextField alloc] initWithFrame:CGRectMake(_phoneNumLabel.frame.size.width, 0, RGTextWidth, RGTextHeihgt)];
    _phoneNumText.font = [UIFont systemFontOfSize:font15];
    _phoneNumText.placeholder = @"请输入手机号码";
    _phoneNumText.font = [UIFont systemFontOfSize:font14];
    _phoneNumText.backgroundColor = [UIColor whiteColor];
    _phoneNumText.layer.cornerRadius = 6;
    _phoneNumText.delegate = self;
    _phoneNumText.layer.borderColor = [UIColor colorWithRed:0.83 green:0.83 blue:0.83 alpha:1].CGColor;
    _phoneNumText.layer.borderWidth = 1;
    _phoneNumText.leftView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, RGInsert/4, RGTextHeihgt)];
    _phoneNumText.leftViewMode = UITextFieldViewModeAlways;
    [phoneView addSubview:_phoneNumText];
    phoneView.frame = CGRectMake(0, 0, _phoneNumLabel.frame.size.width + _phoneNumText.frame.size.width, RGTextHeihgt);
    phoneView.layer.position = CGPointMake(screenWidth/2, phoneView.frame.size.height/2 + RGInsert);
    [scroll addSubview:phoneView];
    //tip
    _phoneTip = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, 66, 66)];
    _phoneTip.text = @"(必填)";
    _phoneTip.font = [UIFont systemFontOfSize:font10];
    _phoneTip.alpha = 0.7;
    [_phoneTip sizeToFit];
    _phoneTip.frame = CGRectMake(phoneView.frame.origin.x + phoneView.frame.size.width - _phoneTip.frame.size.width, phoneView.frame.origin.y + phoneView.frame.size.height, _phoneTip.frame.size.width, _phoneTip.frame.size.height);
    [scroll addSubview:_phoneTip];
    
    //验证码视图
    UIView *idenView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, RGIdenButWidth + RGInsert/4 + RGIdenTextWidth, RGTextHeihgt)];
    //验证码按键
    _idenButton = [UIButton buttonWithType:UIButtonTypeCustom];
    _idenButton.frame = CGRectMake(0, 0, RGIdenButWidth, RGTextHeihgt);
    [_idenButton setAttributedTitle:[[NSMutableAttributedString alloc] initWithString:@"获取验证码" attributes:@{NSFontAttributeName: [UIFont systemFontOfSize:font11], NSForegroundColorAttributeName: [UIColor whiteColor]}] forState:UIControlStateNormal];
    [_idenButton setBackgroundColor:[UIColor colorWithRed:0.3 green:0.69 blue:0.51 alpha:1]];
    NSString *selectedTitle = @"稍等30秒";
    [_idenButton setAttributedTitle:[[NSMutableAttributedString alloc] initWithString:selectedTitle attributes:@{NSFontAttributeName: [UIFont systemFontOfSize:font11], NSForegroundColorAttributeName: [UIColor grayColor]}] forState:UIControlStateSelected];
    [_idenButton addTarget:self action:@selector(getSMSNum) forControlEvents:UIControlEventTouchUpInside];
    [idenView addSubview:_idenButton];
    //验证码输入框
    _idenText = [[UITextField alloc] initWithFrame:CGRectMake(_idenButton.frame.size.width + RGInsert/4, 0, RGIdenTextWidth, RGTextHeihgt)];
    _idenText.font = [UIFont systemFontOfSize:font15];
    _idenText.placeholder = @"请输入验证码";
    _idenText.font = [UIFont systemFontOfSize:font14];
    _idenText.leftView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, RGInsert/4, RGTextHeihgt)];
    _idenText.leftViewMode = UITextFieldViewModeAlways;
    _idenText.layer.cornerRadius = 6;
    _idenText.layer.borderWidth = 1;
    _idenText.delegate = self;
    _idenText.tag = 10;
    _idenText.layer.borderColor = [UIColor colorWithRed:0.83 green:0.83 blue:0.83 alpha:1].CGColor;
    _idenText.backgroundColor = [UIColor whiteColor];
    [idenView addSubview:_idenText];
    idenView.frame = CGRectMake(phoneView.frame.origin.x + (phoneView.frame.size.width - idenView.frame.size.width), _phoneTip.frame.origin.y + _phoneTip.frame.size.height + RGInsert/2, idenView.frame.size.width, idenView.frame.size.height);
    [scroll addSubview:idenView];
    //密码视图
    UIView *pwView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 66, RGTextHeihgt)];
    //密码标题
    _pwLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, 66, 66)];
    //密码的属性字符
    NSMutableAttributedString *pwTitle = [[NSMutableAttributedString alloc] initWithString:@"密尼玛码 : "];
    NSRange ran1 = {0, pwTitle.length};
    NSRange ran2 = {1, 2};
    [pwTitle addAttribute:NSFontAttributeName value:[UIFont systemFontOfSize:font15] range:ran1];
    [pwTitle addAttribute:NSForegroundColorAttributeName value:[UIColor clearColor] range:ran2];
    _pwLabel.attributedText = pwTitle;
    _pwLabel.alpha = 0.7;
    [_pwLabel sizeToFit];
    _pwLabel.layer.position = CGPointMake(_pwLabel.frame.size.width/2, pwView.frame.size.height/2);
    [pwView addSubview:_pwLabel];
    //密码输入框
    _pwText = [[UITextField alloc] initWithFrame:CGRectMake(_pwLabel.frame.size.width, 0, RGTextWidth, RGTextHeihgt)];
    _pwText.secureTextEntry = true;
    _pwText.leftView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, RGInsert/4, RGTextHeihgt)];
    _pwText.font = [UIFont systemFontOfSize:font14];
    _pwText.leftViewMode = UITextFieldViewModeAlways;
    _pwText.backgroundColor = [UIColor whiteColor];
    _pwText.delegate = self;
    _pwText.layer.borderColor = [UIColor colorWithRed:0.83 green:0.83 blue:0.83 alpha:1].CGColor;
    _pwText.layer.borderWidth = 1;
    _pwText.layer.cornerRadius = 6;
    [pwView addSubview:_pwText];
    pwView.frame = CGRectMake(0, 0, _pwLabel.frame.size.width + _pwText.frame.size.width, RGTextHeihgt);
    pwView.layer.position = CGPointMake(screenWidth/2, idenView.frame.origin.y + idenView.frame.size.height + pwView.frame.size.height/2 + RGInsert/2);
    [scroll addSubview:pwView];
    
    //重复密码框
    dupView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 66, RGTextHeihgt)];
    //密码标题
    _dupLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, 66, 66)];
    _dupLabel.text = @"重复密码 : ";
    _dupLabel.font = [UIFont systemFontOfSize:font15];
    _dupLabel.alpha = 0.7;
    [_dupLabel sizeToFit];
    _dupLabel.layer.position = CGPointMake(_dupLabel.frame.size.width/2, dupView.frame.size.height/2);
    [dupView addSubview:_dupLabel];
    //密码输入框
    _dupText = [[UITextField alloc] initWithFrame:CGRectMake(_dupLabel.frame.size.width, 0, RGTextWidth, RGTextHeihgt)];
    _dupText.secureTextEntry = true;
    _dupText.leftView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, RGInsert/4, RGTextHeihgt)];
    _dupText.font = [UIFont systemFontOfSize:font14];
    _dupText.leftViewMode = UITextFieldViewModeAlways;
    _dupText.backgroundColor = [UIColor whiteColor];
    _dupText.delegate = self;
    _dupText.tag = 1;
    _dupText.layer.borderColor = [UIColor colorWithRed:0.83 green:0.83 blue:0.83 alpha:1].CGColor;
    _dupText.layer.borderWidth = 1;
    _dupText.layer.cornerRadius = 6;
    [dupView addSubview:_dupText];
    dupView.frame = CGRectMake(0, 0, _dupLabel.frame.size.width + _dupText.frame.size.width, RGTextHeihgt);
    dupView.layer.position = CGPointMake(screenWidth/2, pwView.frame.origin.y + pwView.frame.size.height + dupView.frame.size.height/2 + RGInsert/4);
    [scroll addSubview:dupView];
    //条款
    UIView *proView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 77, 16)];
    _selectButton = [UIButton buttonWithType:UIButtonTypeCustom];
    _selectButton.frame = CGRectMake(0, 0, 16, 16);
    _selectButton.backgroundColor = [UIColor whiteColor];
    _selectButton.layer.borderWidth = 1;
    _selectButton.layer.borderColor = BGGREEN.CGColor;
    _selectButton.layer.cornerRadius = 4;
    [_selectButton setImage:[UIImage imageNamed:@"check"] forState:UIControlStateSelected];
    [_selectButton addTarget:self action:@selector(selectPro:) forControlEvents:UIControlEventTouchUpInside];
    [proView addSubview:_selectButton];
    //文字
    _proLabel = [[UILabel alloc] initWithFrame:CGRectMake(_selectButton.frame.size.width + RGInsert/5, 0, 66, font11)];
    _proLabel.text = @"我同意";
    _proLabel.font = [UIFont systemFontOfSize:font11];
    _proLabel.alpha = 0.7;
    [_proLabel sizeToFit];
    _proLabel.layer.position = CGPointMake(_proLabel.frame.origin.x + _proLabel.frame.size.width/2, proView.frame.size.height/2);
    [proView addSubview:_proLabel];
    _proButton = [UIButton buttonWithType:UIButtonTypeSystem];
    NSMutableAttributedString *proTitle = [[NSMutableAttributedString alloc] initWithString:@"群智社所有条款"];
    NSRange proRange = {0, proTitle.length};
    [proTitle addAttribute:NSForegroundColorAttributeName value:[UIColor redColor] range:proRange];
    [proTitle addAttribute:NSUnderlineStyleAttributeName value:[NSNumber numberWithInteger:NSUnderlineStyleSingle] range:proRange];
    [proTitle addAttribute:NSFontAttributeName value:[UIFont systemFontOfSize:font11] range:proRange];
    [_proButton setAttributedTitle:proTitle forState:UIControlStateNormal];
    [_proButton addTarget:self action:@selector(provision) forControlEvents:UIControlEventTouchUpInside];
    _proButton.frame = CGRectMake(_proLabel.frame.origin.x + _proLabel.frame.size.width, 0, 8*font11, font11);
    [_proButton sizeToFit];
    _proButton.layer.position = CGPointMake(_proButton.frame.origin.x + _proButton.frame.size.width/2, proView.frame.size.height/2);
    [proView addSubview:_proButton];
    
    proView.frame = CGRectMake(0, 0, _selectButton.frame.size.width + _proLabel.frame.size.width + _proButton.frame.size.width + RGInsert/5, _selectButton.frame.size.height);
    proView.layer.position = CGPointMake(dupView.frame.origin.x + dupView.frame.size.width - proView.frame.size.width + proView.frame.size.width/2, dupView.frame.origin.y + dupView.frame.size.height + RGInsert);
    [scroll addSubview:proView];
    [self.view addSubview:scroll];
    //调整scroll的content高度
    CGSize content = scroll.contentSize;
    content.height = (proView.frame.origin.y + proView.frame.size.height) > screenHeight - 64 ? (proView.frame.origin.y + proView.frame.size.height) : screenHeight - 64 + 1;
    scroll.contentSize = content;
    //底部按键
    _barButton = [[BarButtonView alloc] initWithFrame:CGRectMake(0, screenHeight - BBViewHeight - 64, screenWidth, BBViewHeight) name:@"注册"];
    [_barButton.but addTarget:self action:@selector(userRegister) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:_barButton];
}

#pragma 事件方法

- (void)getSMSNum {
    NSLog(@"发送验证码");
    if(_phoneNumText.text.length != 11) {
        [QYNotice showWarning:@"请输入正确的手机号码" toView:self.view];
        [QYNotice dismissWithDelay:3];
    }
    else {
        if([CoreStatus isNetworkEnable]) {
            [SMSSDK getVerificationCodeByMethod:SMSGetCodeMethodSMS phoneNumber:_phoneNumText.text zone:@"86" customIdentifier:nil result:^(NSError *error) {
                if(!error) {
                    [QYNotice showSuccess:@"验证码发送成功" toView:self.view];
                    [QYNotice dismissWithDelay:3];
                    _idenButton.selected = true;
                    [_idenButton removeTarget:self action:@selector(getSMSNum) forControlEvents:UIControlEventTouchUpInside];
                    time = 30;
                    _idenTimer = [NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(idenSchedule) userInfo:nil repeats:true];
                }
                else {
                    [QYNotice showError:@"验证码发送失败" toView:self.view];
                    [QYNotice dismissWithDelay:3];
                }
            }];
        }
        else {
            [QYNotice showWarning:@"未检测到网络" toView:self.view];
            [QYNotice dismissWithDelay:3];
        }
    }
}

- (void)idenSchedule {
    time--;
    NSString *selectedTitle = @"稍等";
    selectedTitle = [selectedTitle stringByAppendingString:[NSString stringWithFormat:@"%d", time]];
    selectedTitle = [selectedTitle stringByAppendingString:@"秒"];
    [_idenButton setAttributedTitle:[[NSMutableAttributedString alloc] initWithString:selectedTitle attributes:@{NSFontAttributeName: [UIFont systemFontOfSize:font11], NSForegroundColorAttributeName: [UIColor grayColor]}] forState:UIControlStateSelected];
    if(time <= 0) {
        [_idenTimer invalidate];
        _idenButton.selected = false;
        [_idenButton addTarget:self action:@selector(getSMSNum) forControlEvents:UIControlEventTouchUpInside];
    }
}

- (void)back {
    [self dismissViewControllerAnimated:true completion:nil];
}

- (void)selectPro:(id)sender {
    UIButton *but = (UIButton*)sender;
    but.selected = !but.selected;
    NSLog(@"选择");
    NSLog(@"%d", but.selected);
}

- (void)provision {
    NSLog(@"条款");
}

- (NSString*)collectData {
    if([_phoneNumText.text isEqual: @""] || _phoneNumText.text.length != 11) {
        return @"请输入正确的电话号码";
    }
    else if([_idenText.text isEqualToString:@""]) {
        return @"请输入验证码";
    }
    else if([_pwText.text isEqualToString:@""] || [_dupText.text isEqualToString:@""]) {
        return @"请输入密码";
    }
    else if(![_pwText.text isEqualToString:_dupText.text]) {
        return @"两次输入密码不同";
    }
    else if(!_selectButton.isSelected) {
        return @"请阅读并同意群智社条款";
    }
    _data = @{@"username": _phoneNumText.text, @"password": _pwText.text, @"password_verify": _dupText.text, @"nickname": _phoneNumText.text};
    return @"noerror";
}

- (void)userRegister {
    if([CoreStatus isNetworkEnable]) {
        [QYNotice showProcess:@"注册中。。" toView:self.view];
        NSString* errorMsg = [self collectData];
        if([errorMsg isEqualToString:@"noerror"]) {
            [SMSSDK commitVerificationCode:_idenText.text phoneNumber:_data[@"username"] zone:@"86" result:^(NSError *error) {
                if(!error) {
                    AFHTTPSessionManager *manager = [GZNetRequest getPOSTManager];;
                    [manager POST:[GZNetRequest getRegisterURL] parameters:_data progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
                        NSLog(@"%@", responseObject);
                        NSDictionary *userData = (NSDictionary*)responseObject;
                        NSString* status = userData[@"status"];
                        NSDictionary* msg = (NSDictionary*)userData[@"msg"];
                        if(![status isEqualToString:@"success"]) {
                            if([msg[@"phone"] isEqualToString:@"unique"]) {
                                [QYNotice showWarning:@"手机号已被注册" toView:self.view];
                                [QYNotice dismissWithDelay:3];
                            }
                            else {
                                [QYNotice showWarning:@"注册失败" toView:self.view];
                                [QYNotice dismissWithDelay:3];
                            }
                        }
                        else {
                            [QYNotice showSuccess:@"注册成功" toView:self.view];
                            [QYNotice dismissWithDelay:2];
                            NSLog(@"%@", msg);
                            [GZConst delay:2 with:^{
                                [self dismissViewControllerAnimated:true completion:nil];
                            }];
                        }
                    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
                        NSLog(@"未知错误");
                        NSLog(@"%@", error);
                        [QYNotice showError:@"未知错误" toView:self.view];
                        [QYNotice dismissWithDelay:2];
                        [GZConst delay:2 with:^{
                            [self dismissViewControllerAnimated:true completion:nil];
                        }];
                    }];
                }
                else {
                    [QYNotice showError:@"短信验证失败" toView:self.view];
                    [QYNotice dismissWithDelay:3];
                }
            }];
        }
        else {
            [QYNotice showError:errorMsg toView:self.view];
            [QYNotice dismissWithDelay:3];
        }
    }
    else {
        [QYNotice showWarning:@"未检测到网络" toView:self.view];
    }
}

- (void)endEditTap {
    [self.view endEditing:true];
}

//键盘监听事件

-(void)keyboardWillShow:(NSNotification*)notification {
    NSDictionary *notifiInfo = notification.userInfo;
    CGFloat keyboardHeight = [[notifiInfo objectForKey:UIKeyboardFrameEndUserInfoKey] CGRectValue].size.height;
    CGRect viewFrame = viewOrigin;
    CGFloat adjust = textBottom - (screenHeight - keyboardHeight - 64);
    if (adjust > 0) {
        viewFrame.origin.y -= adjust;
        [UIView animateWithDuration:0.3 animations:^{
            self.view.frame = viewFrame;
        }];
    }
    else {
        [UIView animateWithDuration:0.3 animations:^{
            self.view.frame = viewOrigin;
        }];
    }
}

-(void)keyboardWillHide:(NSNotification*)notification {
    [UIView animateWithDuration:0.3 animations:^{
        self.view.frame = viewOrigin;
    }];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

-(void)scrollViewWillBeginDragging:(UIScrollView*)scrollView {
    [self endEditTap];
}

-(void)textFieldDidBeginEditing:(UITextField *)textField {
    if (textField.tag == 1) {
        textBottom = scroll.frame.origin.y + dupView.frame.origin.y + textField.frame.origin.y + textField.frame.size.height;
    }
    else {
        textBottom = 0;
    }
}

@end
